import { createRouter, createWebHashHistory } from 'vue-router';
import menu from './menu.js';
import storage from '../utils/storage';
import pinia from '@/pinia/index';
import { systemStore } from '@/pinia/system';
import { storeToRefs, mapActions } from 'pinia';

const routes = [...menu];
const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
});

//判断当前地址是否可以访问
async function checkPermission(path) {
  //loadAsyncRoutes()
  let hsaPermission = router.getRoutes().filter(route => route.path == path).length;
  if (hsaPermission) {
    return true;
  } else {
    //再次判断当前地址是否可以访问
    hsaPermission = router.getRoutes().filter(route => route.path == path).length;
    if (hsaPermission) {
      return true;
    }
    return false;
  }
}
router.beforeEach(async (to, from, next) => {
  const store = systemStore();
  if (store.flag == 0 && !hasNecessaryRoute(to)) {
    //try防止接口报错
    try {
      //同步方法 初始化路由
      await store.initRouter();
      store.flag = 1;
      //添加动态路由
      addRoute(store.routes);
      next({ ...to, replace: true });
    } catch (e) {
      console.log('获取菜单失败', e);
      store.flag = 0;
      //获取菜单失败，跳转错误界面
      next('/error');
    }
  } else {
    if (!hasNecessaryRoute(to)) {
      //获取菜单失败，跳转错误界面
      next('/error');
    }
    document.title = to.meta.title;
    next();
  }
});
//缓存添加路由
function addRoute(routes) {
  for (let route of routes) {
    if (route == null) {
      continue;
    }
    if (router.hasRoute(route.name)) {
      continue;
    }
    console.log(route);
    router.addRoute(route.spaceZone, {
      path: route.routerPath,
      meta: { title: route.menuName },
      name: route.menuCode || route.menuId,
      component: () => import('@/views/' + `${route.filePath}` + '.vue'),
    });
  }
}
//判断路由是否存在当前跳转
function hasNecessaryRoute(to) {
  let is = router.getRoutes().filter(route => route.path == to.path).length;
  if (router.hasRoute(to.name) || router.getRoutes().filter(route => route.path == to.path) > 0) {
    return true;
  } else {
    return false;
  }
}

export default router;
